package org.example;

import org.example.service.WelcomeService;

import java.util.Iterator;
import java.util.ServiceLoader;

public class Main {
    public static void main(String[] args) {
        ServiceLoader<WelcomeService> loader = ServiceLoader.load(WelcomeService.class);
        ClassLoader classLoader = ServiceLoader.class.getClassLoader();
        System.out.println("classLoader: " + classLoader); // 输出："classLoader: null"，这证明java.util.ServiceLoader这个类是有引导类加载器加载的
        Iterator<WelcomeService> iterator = loader.iterator();
        while (iterator.hasNext()){
            // java.util.ServiceLoader.ProviderImpl.newInstance()方法中会通过反射调用服务提供者类的构造器创建对应的实例，
            // 因此这里返回的是org.example.service.impl.ChineseWelcomeService的实例
            WelcomeService welcomeService = iterator.next();
            welcomeService.sayHello("张三"); // 输出：张三你好！欢迎光临！和 Hello 张三, welcome !
        }
    }
}